<template>
  <div class="cascade">
    <div class="radioCell">
      <u-search placeholder="请键入搜索" v-model="keyword" :showAction="false" actionText="搜索" :animation="true" :clearabled="false" @change="search" @search="search" @clear="search"></u-search>

      <u-radio-group v-model="professional" placement="column" @change="groupChange($event)">
        <u-radio v-for="(item, index) in list" :key="index" :label="item.label" :name="item.value" :style="{ 'margin-left': item.left ? '32rpx' : '0', 'margin-top': '20rpx' }">
        </u-radio>
      </u-radio-group>
    </div>
  </div>
</template>

<script>
import {getMajorList} from "@/api/user";
export default {
  data() {
    return {
      allList: [],
      list: [],
      professional: "",
      keyword: "",
      debounceTimer: null
    };
  },
  onLoad(options) {
    const params = options.params || '';
    this.professional = options.major || options.subMajor
    this.init(params)
    this.$nextTick(() => {
      const searchText = uni.getStorageSync('searchMajor') || ''
      if (searchText) {
        this.keyword = searchText
      }
    })
  },
  mounted() {
  },
  methods: {
    async init(params) {
      const {data} = await getMajorList(params)
      this.list = data
        .map((item) => {
          let child = [];
          if (item.children) {
            child = [...item.children.map((v) => ({ ...v, left: true }))];
            delete item.children;
            child = [item, ...child];
            return child;
          }
          return item;
        })
        .flat();
      this.allList = [...this.list];
    },
    search() {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer)
      }
      this.debounceTimer = setTimeout(() => {
        this.debounceTimer = null
        if (this.keyword) {
          const list = this.allList.filter((item) => item.label.includes(this.keyword));
          this.list = Array.from(new Set(list.map((item) => JSON.stringify(item)))).map((item) => JSON.parse(item));
        } else {
          this.list = [...this.allList];
        }
        uni.setStorageSync('searchMajor', this.keyword)
      }, 200)
    },
    groupChange(e) {
      uni.$emit("updateProfessional", { professional: e, child: !e.includes("类") });
      setTimeout(() => {
        this.leftClick()
      }, 200)
    },
    leftClick() {
      uni.navigateBack({
        delta: 1,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.cascade {
  padding: 32rpx;
  padding-top: 80rpx;
}
</style>
